package ui;


import entity.User;
import entity.Order;
import entity.Item;
import service.UserService;
import service.OrderService;
import service.ItemService;

import java.util.List;
import java.util.Scanner;

/**
 * 控制台用户界面 (Console User Interface)
 */
public class ConsoleUI {
    private Scanner scanner;
    private UserService userService;
    private OrderService orderService;
    private ItemService itemService;
    private User currentUser;

    /*构 造 初始化界面所需要的所有工具*/
    public ConsoleUI() {
        this.scanner = new Scanner(System.in);
        this.userService = new UserService();
        this.orderService = new OrderService();
        this.itemService = new ItemService();
        /*初始化时，默认没有用户在登录*/
        this.currentUser = null;
    }

    public void start() {
        System.out.println("=== 欢迎使用二手交易平台 ===");
        while (true) {
            /*没登陆就主页面*/
            if (currentUser == null) {
                showMainMenu();
            } else {
                /*登陆了就用户界面*/
                showUserMenu();
            }
        }
    }

    /*主页面*/
    private void showMainMenu() {
        System.out.println("\n=== 主菜单 ===");
        System.out.println("1. 用户登录");
        System.out.println("2. 用户注册");
        System.out.println("3. 浏览商品");
        System.out.println("4. 搜索商品");
        System.out.println("5. 退出系统");
        System.out.print("请选择操作: ");
        int choice = getIntInput();
        switch (choice) {
            case 1:
                login();
                break;
            case 2:
                register();
                break;
            case 3:
                browseItems();
                break;
            case 4:
                searchItems();
                break;
            case 5:
                System.out.println("感谢使用，再见！");
                System.exit(0);
            default:
                System.out.println("无效选择，请重新输入！");
        }
    }

    private void showUserMenu() {
        // 显示当前登录的用户名，让用户知道自己是谁
        System.out.println("\n=== 用户菜单 (" + currentUser.getUsername() + ") ===");
        System.out.println("1. 发布商品");
        System.out.println("2. 我的商品");
        System.out.println("3. 购买商品");
        System.out.println("4. 我的订单");
        System.out.println("5. 浏览商品");
        System.out.println("6. 搜索商品");
        System.out.println("7. 退出登录");
        System.out.print("请选择操作: ");

        int choice = getIntInput();
        switch (choice) {
            case 1:
                publishItem();
                break;
            case 2:
                showMyItems();
                break;
            case 3:
                purchaseItem();
                break;
            case 4:
                showMyOrders();
                break;
            case 5:
                browseItems();
                break;
            case 6:
                searchItems();
                break;
            case 7:
                currentUser = null;
                System.out.println("已退出登录");
                break;
            default:
                System.out.println("无效选择，请重新输入！");
        }
    }

    /*用户登录功能的方法*/
    private void login() {
        System.out.println("\n=== 用户登录 ===");
        System.out.print("用户名: ");
        String username = scanner.nextLine();
        System.out.print("密码: ");
        String password = scanner.nextLine();

        /*验证密码还有账号的对错*/
        User user = userService.loginUser(username, password);

        if (user != null) {
            currentUser = user;
            System.out.println("登录成功！ 欢迎" + username);
        } else {
            System.out.println("登录失败！用户名或密码错误");
        }
    }

    /*用户注册*/
    private void register() {
        System.out.println("\n=== 用户注册 ===");
        System.out.print("用户名: ");
        String username = scanner.nextLine();
        System.out.print("密码: ");
        String password = scanner.nextLine();
        System.out.print("电话: ");
        String phone = scanner.nextLine();
        System.out.print("邮箱: ");
        String email = scanner.nextLine();

        /*完成注册*/
        if (userService.registerUser(username, password, phone, email)) {
            System.out.println("注册成功！");
        } else {
            System.out.println("注册失败！");
        }
    }

    /*发布商品*/
    private void publishItem() {
        if (currentUser == null) {
            System.out.println("请先登录！");
        }
        System.out.println("\n=== 发布商品 ===");
        System.out.print("商品名称: ");
        String name = scanner.nextLine();
        System.out.print("价格: ");
        double price = getDoubleInput(); // 读取价格（确保是数字）
        System.out.print("分类: ");
        String category = scanner.nextLine();
        System.out.print("描述: ");
        String description = scanner.nextLine();
        System.out.print("使用时间(月): ");
        int usageMonths = getIntInput(); // 读取使用月数（确保是整数）
        System.out.print("商品状况: ");
        String condition = scanner.nextLine();

        /*实现商品发布 传到当前登录的id里*/
        if (itemService.publishItem(currentUser.getUserId(), name, price, category,
                description, usageMonths, condition)) {
            System.out.println("商品发布成功！");
        } else {
            System.out.println("商品发布失败！");
        }
    }

    /*浏览*/
    private void browseItems() {
        System.out.println("\n=== 浏览商品 ===");
        //获取所有在售商品
        List<Item> items = itemService.getAllItems();
        if (items.isEmpty()) {
            System.out.println("暂无商品！");
            return;
        }
        // 循环遍历商品列表
        for (int i = 0; i < items.size(); i++) {
            Item item = items.get(i);
            System.out.println((i + 1) + ". " + item.getName() + " - ¥" + item.getPrice() +
                    " [" + item.getCategory() + "]");
        }
        System.out.println("\n输入商品编号查看详情，输入0返回: ");
        int choice = getIntInput();

        // 如果用户输入的编号有效（在1到商品总数之间）
        if (choice > 0 && choice <= items.size()) {
            // 根据编号获取对应的商品
            Item item = items.get(choice - 1);
            item.displayDetails();

            // 如果用户已登录，并且这个商品不是用户自己发布的
            if (currentUser != null && currentUser.getUserId() != item.getUserId()) {
                System.out.print("是否购买此商品？(y/n): ");
                String answer = scanner.nextLine();
                if ("y".equalsIgnoreCase(answer)) { // 忽略大小写
                    // 调用购买商品的方法
                    purchaseItem(item.getItemId());
                }
            }
        }
    }

    /*搜索商品*/
    private void searchItems() {
        System.out.println("\n=== 搜索商品 ===");
        System.out.print("请输入关键词: ");
        String keyword = scanner.nextLine();
        //根据关键词搜索商品
        List<Item> items = itemService.searchItems(keyword);
        if (items.isEmpty()) {
            System.out.println("未找到相关商品！");
            return;
        }
        //结果
        System.out.println("找到 " + items.size() + " 个相关商品:");
        for (int i = 0; i < items.size(); i++) {
            Item item = items.get(i);
            System.out.println((i + 1) + ". " + item.getName() + " - ¥" + item.getPrice() +
                    " [" + item.getCategory() + "]");
        }
    }

    /*查看我的商品*/
    private void showMyItems() {
        if (currentUser == null) {
            System.out.println("请先登录！");
            return;
        }

        System.out.println("\n=== 我的商品 ===");
        //获取当前用户发布的所有商品
        List<Item> items = itemService.getItemsByUserId(currentUser.getUserId());
        if (items.isEmpty()) {
            System.out.println("您还没有发布商品！");
            return;
        }
        // 显示用户自己的商品
        for (int i = 0; i < items.size(); i++) {
            Item item = items.get(i);
            System.out.println((i + 1) + ". " + item.getName() + " - ¥" + item.getPrice() +
                    " [" + item.getStatus() + "]");
        }
    }

    /*购买*/
    private void purchaseItem() {
        if (currentUser == null) {
            System.out.println("请先登录！");
            return;
        }

        System.out.println("\n=== 购买商品 ===");
        System.out.print("请输入商品ID: ");
        int itemId = getIntInput();

        //重载purchaseTtem方法 传入商品ID
        purchaseItem(itemId);
    }

    private void purchaseItem(int itemId) {
        if (currentUser == null) {
            System.out.println("请先登录！");
            return;
        }

        // 先获取商品的详细信息，用于检查和确认
        Item item = itemService.getItemById(itemId);
        if (item == null) {
            System.out.println("商品不存在！");
            return;
        }

        //不能购买自己发布的商品
        if (item.getUserId() == currentUser.getUserId()) {
            System.out.println("不能购买自己发布的商品！");
            return;
        }

        // 显示商品详情
        item.displayDetails();
        System.out.print("确认购买？(y/n): ");
        String answer = scanner.nextLine();

        if ("y".equalsIgnoreCase(answer)) {
            //创建订单
            if (orderService.createOrder(currentUser.getUserId(), itemId)) {
                System.out.println("购买成功！订单已创建。");
            } else {
                System.out.println("购买失败！");
            }
        }
    }


    /*查看我的订单*/
    private void showMyOrders() {
        if (currentUser == null) {
            System.out.println("请先登录！");
            return;
        }

        System.out.println("\n=== 我的订单 ===");
        //获取当前用户的所有订单
        List<Order> orders = orderService.getOrdersByBuyerId(currentUser.getUserId());

        if (orders.isEmpty()) {
            System.out.println("您还没有订单！");
            return;
        }

        // 显示每个订单
        for (int i = 0; i < orders.size(); i++) {
            Order order = orders.get(i);
            // 根据订单中的商品ID，获取商品信息
            Item item = itemService.getItemById(order.getItemId());
            System.out.println((i + 1) + ". 订单ID: " + order.getOrderId() +
                    ", 商品: " + (item != null ? item.getName() : "未知") + // 如果商品不存在，显示“未知”
                    ", 金额: ¥" + order.getTotalAmount() +
                    ", 状态: " + order.getStatus());
        }

        // 取消订单的功能
        System.out.println("\n1. 取消订单");
        System.out.println("2. 返回");
        System.out.print("请选择: ");

        int choice = getIntInput();
        if (choice == 1) {
            System.out.print("请输入要取消的订单ID: ");
            int orderId = getIntInput();
            //实现取消订单
            if (orderService.cancelOrder(orderId)) {
                System.out.println("订单取消成功！");
            } else {
                System.out.println("订单取消失败！");
            }
        }
    }
    /*确保输入正确 数字，小数*/
    private int getIntInput() {
        while (true) {
            try {
                //把用户输入的字符串转换成整数
                return Integer.parseInt(scanner.nextLine());
            } catch (NumberFormatException e) {
                // 如果没哟转换成功，就提示用户重新输入
                System.out.print("请输入有效的数字: ");
            }
        }
    }
    private double getDoubleInput() {
        while (true) {
            try {
                return Double.parseDouble(scanner.nextLine());
            } catch (NumberFormatException e) {
                System.out.print("请输入有效的价格: ");
            }
        }
    }
}